package com.erp.order.purchasing.service.impl;

import com.erp.hr.base.service.impl.BaseServiceImpl;
import com.erp.hr.base.util.CommonUtils;
import com.erp.hr.base.vo.LegalityResultVO;
import com.erp.hr.base.vo.ResultVO;
import com.erp.hr.dao.model.HrStaffInfoRO;
import com.erp.order.purchasing.dao.PurchasingRequisitionDao;
import com.erp.order.purchasing.model.PurchasingRequisition;
import com.erp.order.purchasing.model.PurchasingRequisitionDetail;
import com.erp.order.purchasing.service.PurchasingRequisitionDetailService;
import com.erp.order.purchasing.service.PurchasingRequisitionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 采购申请 业务实现层
 * @Author: syz
 * @blame syz
 * @CreateTime: 2021/4/6
 */
@Service
public class PurchasingRequisitionServiceImpl extends BaseServiceImpl<PurchasingRequisitionDao, PurchasingRequisition> implements PurchasingRequisitionService {

    /**
     * 申请详情服务
     */
    @Lazy
    @Autowired
    private PurchasingRequisitionDetailService purchasingRequisitionDetailService;


    /**
     * 初始化创建信息
     * @param purchasingRequisition 需要初始化创建信息的对象
     */
    @Override
    public void initCreateInfo(PurchasingRequisition purchasingRequisition) {
        HrStaffInfoRO staffInfo = getStaffInfo();
        if (staffInfo != null) {
            purchasingRequisition.setCreateUserName(staffInfo.getStaffName());
            purchasingRequisition.setCompanyCode(staffInfo.getCompanyCode());
            purchasingRequisition.setCompanyName(staffInfo.getCompanyName());
            purchasingRequisition.setDepartmentCode(staffInfo.getDepartmentCode());
            purchasingRequisition.setDepartmentName(staffInfo.getDepartmentName());
            purchasingRequisition.setTel(staffInfo.getStaffMobile());
            purchasingRequisition.setLandLine(staffInfo.getStaffTel());
            purchasingRequisition.setMailbox(staffInfo.getStaffEmail());
            purchasingRequisition.setAddress(staffInfo.getAddress());
        }
    }

    /**
     * 为单个对象添加完整信息
     * @param purchasingRequisition 需要添加完整信息的对象
     * @return 添加完整信息后的对象
     */
    @Override
    public PurchasingRequisition addCompleteData(PurchasingRequisition purchasingRequisition) {
        if (StringUtils.isNotEmpty(purchasingRequisition.getAccessory())) {
            String[] files = purchasingRequisition.getAccessory().split("FILE_NAME_END");
            Map<String, String> map = new HashMap<>(files.length);
            for (String file : files) {
                map.put(file, file.split("FILE_NAME_START")[1]);
            }
            purchasingRequisition.setFileMap(map);
        }
        purchasingRequisition.setSubs(purchasingRequisitionDetailService.addCompleteData(
                purchasingRequisitionDetailService.getListByRequisitionId(purchasingRequisition.getId())));
        return purchasingRequisition;
    }

    /**
     * 为集合添加完整信息
     * @param list 需要添加完整信息的集合
     * @return 添加完整信息后的集合
     */
    @Override
    public List<PurchasingRequisition> addCompleteData(List<PurchasingRequisition> list) {
        return list;
    }

    /**
     * 校验数据合法性
     * @param purchasingRequisition 需要校验的对象
     * @return 校验结果
     */
    @Override
    public LegalityResultVO isLegalityData(PurchasingRequisition purchasingRequisition) {
        if (StringUtils.isBlank(purchasingRequisition.getTel())) {
            return new LegalityResultVO(true, "请输入手机号码!");
        }
        if (!purchasingRequisition.getTel().matches(CommonUtils.PHONE_REGEX)) {
            return new LegalityResultVO(true, "请输入正确的联系电话!");
        }
        try {
            if (new SimpleDateFormat(CommonUtils.YEAR_MONTH_DAY).parse(purchasingRequisition.getScheduledTime()).getTime() <= System.currentTimeMillis()) {
                return new LegalityResultVO(true, "期望交货时间必须晚于当前时间!");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new LegalityResultVO(false, null);
    }

    /**
     * 保存对象
     * @param purchasingRequisition 需要保存的对象
     * @return 保存结果
     */
    @Override
    public boolean save(PurchasingRequisition purchasingRequisition) {
        try {
            setCode(purchasingRequisition);
            purchasingRequisition.setAllowedWithdraw(CommonUtils.IS_DEL_YES);
            purchasingRequisition.setStatus(CommonUtils.PURCHASING_REQUISITION_STATUS_DRAFT);
            insertDataObject(purchasingRequisition);
            List<PurchasingRequisitionDetail> subs = purchasingRequisition.getSubs();
            for (PurchasingRequisitionDetail sub : subs) {
                if (sub.getAccessory() == null) {
                    sub.setAccessory("");
                }
                sub.setRequisitionId(purchasingRequisition.getId());
                sub.setStatus(CommonUtils.PURCHASING_REQUISITION_DETAI_STATUS_DRAFT);
                setCreateInfo(sub);
                purchasingRequisitionDetailService.insertDataObject(sub);
            }
            return true;
        } catch (RuntimeException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 更新对象
     * @param purchasingRequisition 需要更新的对象
     * @return 更新结果
     */
    @Override
    public boolean update(PurchasingRequisition purchasingRequisition) {
        try {
            setUpdateInfo(purchasingRequisition);
            updateDataObject(purchasingRequisition);
            List<PurchasingRequisitionDetail> subs = purchasingRequisition.getSubs();
            for (PurchasingRequisitionDetail sub : subs) {
                if (sub.getAccessory() == null) {
                    sub.setAccessory("");
                }
                if (sub.getId() != -1) {
                    setUpdateInfo(sub);
                    purchasingRequisitionDetailService.updateDataObject(sub);
                } else {
                    sub.setRequisitionId(purchasingRequisition.getId());
                    sub.setStatus(CommonUtils.PURCHASING_REQUISITION_DETAI_STATUS_DRAFT);
                    setCreateInfo(sub);
                    purchasingRequisitionDetailService.insertDataObject(sub);
                }
            }
            List<Long> ids = purchasingRequisition.getIds();
            for (Long id : ids) {
                purchasingRequisitionDetailService.linkDelete(id);
            }
            return true;
        } catch (RuntimeException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 提交
     * @param id 需要提交对象的id
     * @return 提交结果
     */
    @Override
    public ResultVO<String> submit(Long id) {
        PurchasingRequisition pr = dao.getDataObject(id.toString());
        if (CommonUtils.PURCHASING_REQUISITION_TYPE_MONTH.equals(pr.getType())) {
            if (!CommonUtils.isApplicationPeriod()) {
                return ResultVO.error("不在月采购申请提交期间!");
            }
            if (dao.isResubmit(getStaffCodeByDepartment(pr.getDepartmentCode()))) {
                return ResultVO.error("不可多次提交月采购申请!");
            }
        }
        pr.setStatus(CommonUtils.PURCHASING_REQUISITION_STATUS_SUBMIT);
        setUpdateInfo(pr);
        dao.updateDataObject(pr);
        List<PurchasingRequisitionDetail> list = purchasingRequisitionDetailService.getListByRequisitionId(id);
        for (PurchasingRequisitionDetail prd : list) {
            prd.setStatus(CommonUtils.PURCHASING_REQUISITION_DETAIL_STATUS_SEARCH_SOURCE);
            setUpdateInfo(prd);
            purchasingRequisitionDetailService.updateDataObject(prd);
        }
        return ResultVO.success();
    }

    /**
     * 撤回
     * @param id 需要撤回对象的id
     * @return 撤回结果
     */
    @Override
    public ResultVO<String> recall(Long id) {
        PurchasingRequisition pr = dao.getDataObject(id.toString());
        if (CommonUtils.IS_DEL_NO.equals(pr.getAllowedWithdraw())) {
                return ResultVO.error("不可撤回!");
        }
        pr.setStatus(CommonUtils.PURCHASING_REQUISITION_STATUS_DRAFT);
        setUpdateInfo(pr);
        dao.updateDataObject(pr);
        List<PurchasingRequisitionDetail> list = purchasingRequisitionDetailService.getListByRequisitionId(id);
        for (PurchasingRequisitionDetail prd : list) {
            prd.setStatus(CommonUtils.PURCHASING_REQUISITION_DETAI_STATUS_DRAFT);
            setUpdateInfo(prd);
            purchasingRequisitionDetailService.updateDataObject(prd);
        }
        return ResultVO.success();
    }

    /**
     * 根据id删除对象及相关信息
     * @param id 需要删除对象的id
     * @return 删除结果
     */
    @Override
    public boolean linkDelete(Long id) {
        PurchasingRequisition pr = dao.getDataObject(id.toString());
        pr.setIsDel(CommonUtils.IS_DEL_YES);
        setUpdateInfo(pr);
        dao.updateDataObject(pr);
        List<PurchasingRequisitionDetail> list = purchasingRequisitionDetailService.getListByRequisitionId(id);
        for (PurchasingRequisitionDetail prd : list) {
            prd.setIsDel(CommonUtils.IS_DEL_YES);
            setUpdateInfo(prd);
            purchasingRequisitionDetailService.updateDataObject(prd);
        }
        return true;
    }

    /**
     * 设置申请编号
     * @param purchasingRequisition 需要设置申请编号的对象
     */
    private void setCode(PurchasingRequisition purchasingRequisition) {
        StringBuilder sb = new StringBuilder();
        if (CommonUtils.PURCHASING_REQUISITION_TYPE_SPORADIC.equals(purchasingRequisition.getType())) {
            sb.append(CommonUtils.PREFIX_SPORADIC);
        } else {
            sb.append(CommonUtils.PREFIX_MONTH);
        }
        Calendar calendar = Calendar.getInstance();
        sb.append(calendar.get(Calendar.YEAR));
        sb.append(calendar.get(Calendar.MONTH) + 1);
        if (CommonUtils.PURCHASING_REQUISITION_TYPE_SPORADIC.equals(purchasingRequisition.getType())) {
            sb.append(calendar.get(Calendar.DATE));
        }
        sb.append(getCodeSuffix(purchasingRequisition.getType()));
        purchasingRequisition.setCode(sb.toString());
    }

    /**
     * 获取申请编号后缀
     * @param type 申请类型
     * @return 申请编号后缀
     */
    private String getCodeSuffix(String type) {
        Integer num = dao.getRequisitionCount(type) + 1;
        String suffix = num.toString();
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < CommonUtils.PURCHASING_REQUISITION_LENGRH - suffix.length(); i ++) {
            result.append("0");
        }
        result.append(suffix);
        return result.toString();
    }

}